<template>
  <div class="city-wrapper">
    <van-nav-bar title="城市选择" left-arrow @click-left="onClickLeft" />
    <div class="city-wrapper-main">
        <van-index-bar :index-list="indexList" :sticky="false">
            <div v-for="(item,keys) in cityList" :key="keys" class="city-group-item">
                <van-index-anchor :index="keys" class="anchor"/>
                <van-cell v-for="v in item" :title="v.label" :key="v.label" @click="changeCity(v)" />
            </div>
        </van-index-bar>
    </div>
  </div>
</template>

<script>
import {mapMutations} from 'vuex';
export default {
  data() {
    return {
      indexList: [],
      cityList:[],
    };
  },
  created() {
      this.getCity();
  },
  methods: {
    ...mapMutations('city',['setCity']),
    onClickLeft() {
      this.$router.go(-1);
    },
    async getCity() {
        const {data} = await this.$http.getCityList();
        this.cityList = this.filterCityList(data.body);
    },
    changeCity(v){
      console.log(v);
      ///sadsdasdasdsdsadsad
      this.setCity(v);
      this.$router.go(-1);
    },
    filterCityList(arr){
        let newCityKeys = new Set([]);
        let newCityList = {};
        arr.forEach(item => {
            newCityKeys.add(item.short.slice(0,1).toUpperCase())
        });
        this.indexList = [...newCityKeys].sort();
        for (const key of this.indexList) {
          newCityList[key]=arr.filter(item=>item.short.slice(0,1).toUpperCase()==key);
        }
        return newCityList;
    },
  },
};
</script>

<style lang="less">
.city-wrapper{
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    .city-wrapper-main{
        flex: 1;
        overflow-y:auto;
        .anchor{
            background: #F7F8FA;
        }
    }
}
</style>